# -*- coding:utf-8 -*-

from tornado import web, gen
import os

from appcommon.framework import APIRequestHandler
from appcommon import checktool
from common import utiltool
import models as userm
from couch import models as couchm
from common import timetool
import settings
from pay import models as paym
from pay import tools as payt
from wechat import models as wechatm


class SignHandler(APIRequestHandler):
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        current_time = timetool.get_timestamp()
        phone = self.get_argument('phone', '')
        device_type = self.get_argument('device_type', '')
        device_token = self.get_argument('device_token', '')
        client_id = self.get_argument('client_id', '')
        version = self.get_argument('version', '1.0')
        area = self.get_argument('area', '')
        if phone:
            yield userm.update_user_area(phone, area)
        yield userm.save_sign_log(phone, device_type, client_id, current_time, version, device_token)
        yield userm.update_client_id(phone, device_type, client_id, current_time, device_token)
        is_vip1 = yield userm.check_phone_is_vip1(phone, current_time)
        is_vip4 = yield userm.check_phone_is_vip4(phone, current_time)
        is_silence = yield userm.check_phone_is_silence(phone)
        is_couch = yield couchm.get_couch_auth_status(phone)
        is_bmt = yield couchm.check_is_open_bmt(phone)
        is_student = yield couchm.check_is_student(phone)
        nick_name = ""
        avatar = ""
        phone_code = ""
        if phone:
            user_info = yield userm.get_userinfo_with_phone(phone)
            if user_info:
                nick_name = user_info['nick_name']
                avatar = user_info['avatar']
                phone_code = user_info['phone_code']
        if is_couch:
            couch_sign_added = yield userm.check_couch_sign_added(phone)
            if not couch_sign_added:
                yield couchm.add_couch_score(phone, u'签到', 'sign', 2)
        res = {
            "code": "0",
            "is_vip1": is_vip1,
            "is_vip4": is_vip4,
            "is_silence": is_silence,
            "is_couch": str(is_couch),
            "is_bmt": str(is_bmt),
            "is_student": str(is_student),
            "nick_name": nick_name,
            "avatar": avatar,
            "phone_code": phone_code
        }
        utiltool.response_write(self, res)


class PhoneLoginHandler(APIRequestHandler):
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        print self.request.arguments
        current_time = timetool.get_timestamp()
        phone = self.get_argument('phone', '')
        from_code = self.get_argument('from_code', '')
        device_type = self.get_argument('device_type', '1')
        user_info = yield userm.get_userinfo_with_phone(phone)
        if user_info:
            del (user_info['flag'])
            if from_code == user_info['phone_code']:
                from_code = ""
            yield userm.update_login_info(phone, device_type, current_time, from_code)

        else:
            sj_name = yield userm.get_sj_nick_name()
            yield userm.add_user_info(0, phone, '', sj_name, settings.DEFAULT_AVATAR, 2, current_time, device_type, from_code)
            user_info = dict(
                phone=phone,
                nick_name=sj_name,
                avatar=settings.DEFAULT_AVATAR
            )
            yield userm.add_score_after_zhuce(phone)
        is_vip1 = yield userm.check_phone_is_vip1(phone, current_time)
        is_vip4 = yield userm.check_phone_is_vip4(phone, current_time)
        user_info['is_vip1'] = is_vip1
        user_info['is_vip4'] = is_vip4

        res = {"code": "0", "info": user_info}
        utiltool.response_write(self, res)


class OtherLoginHandler(APIRequestHandler):
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        print self.request.arguments
        current_time = timetool.get_timestamp()
        device_type = self.get_argument('device_type', '1')
        client_id = self.get_argument('client_id', '')
        openid = self.get_argument('openid', '')
        nick_name = self.get_argument('nick_name', '')
        avatar = self.get_argument('avatar', '')
        platform_type = self.get_argument('platform_type', '')
        from_code = self.get_argument('from_code', '')

        user_info = yield userm.get_userinfo_with_openid(openid)

        if user_info:
            flag = user_info['flag']
            del (user_info['flag'])
            if from_code == user_info['phone_code']:
                from_code = ""
            del user_info['phone_code']
            yield userm.update_user_info(flag, openid, nick_name, avatar, current_time, device_type, platform_type, from_code)
            is_vip1 = yield userm.check_phone_is_vip1(user_info['phone'], current_time)
            is_vip4 = yield userm.check_phone_is_vip4(user_info['phone'], current_time)
            user_info['is_vip1'] = is_vip1
            user_info['is_vip4'] = is_vip4
            res = {"code": "0", "info": user_info}
        else:
            res = {"code": "1", "msg": u"未绑定手机号"}
        utiltool.response_write(self, res)


class BindPhoneHandler(APIRequestHandler):
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        print self.request.arguments
        current_time = timetool.get_timestamp()
        phone = self.get_argument('phone', '')
        device_type = self.get_argument('device_type', '1')
        from_code = self.get_argument('from_code', '')
        openid = self.get_argument('openid', '')
        nick_name = self.get_argument('nick_name', '')
        avatar = self.get_argument('avatar', '')
        platform_type = self.get_argument('platform_type', '')

        user_info = yield userm.get_userinfo_with_phone(phone)
        flag = 1
        is_first_login = 1
        if user_info:
            is_first_login = 0
            flag = user_info['flag']
            del (user_info['flag'])
            if from_code == user_info['phone_code']:
                from_code = ""
            if not flag:
                nick_name = user_info['nick_name']
                avatar = user_info['avatar']
            yield userm.del_user_info_with_phone(phone)
        yield userm.add_user_info(flag, phone, openid, nick_name, avatar, platform_type, current_time, device_type, from_code)
        is_vip1 = yield userm.check_phone_is_vip1(phone, current_time)
        is_vip4 = yield userm.check_phone_is_vip4(phone, current_time)
        if is_first_login:
            yield userm.add_score_after_zhuce(phone)
        res = {"code": "0", "info":
            {"phone": phone, "nick_name": nick_name, "avatar": avatar, "is_vip1": is_vip1, "is_vip4": is_vip4}}
        utiltool.response_write(self, res)


class UpdateUserInfoHandler(APIRequestHandler):
    """修改头像昵称"""
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        current_time = timetool.get_timestamp()
        phone = self.get_argument('phone', '')
        nick_name = self.get_argument('nick_name', '')
        images = []
        if self.request.files:
            file_metas = self.request.files['file']
            for i, meta in enumerate(file_metas):
                upload_path = settings.IMG_BASE_PATH + 'avatar/'
                os.path.exists('upload_path')
                filename = str(phone) + '_' + str(current_time) + '.' + meta['filename'].split('.')[-1]
                filepath = os.path.join(upload_path, filename)
                with open(filepath, 'wb') as up:  # 有些文件需要已二进制的形式存储，实际中可以更改
                    up.write(meta['body'])
                images.append(settings.IMG_BASE_URL + 'avatar/{}'.format(filename))
        avatar = yield userm.update_avatar_nick(phone, nick_name, images, current_time)
        res = dict(code="0", avatar=avatar, nick_name=nick_name)
        utiltool.response_write(self, res)


class AddScoreHandler(APIRequestHandler):
    """加积分"""
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        current_time = timetool.get_timestamp()
        phone = self.get_argument('phone', '')
        ADD_SCORE_AFTER_SHARE = 1
        if ADD_SCORE_AFTER_SHARE:
            is_vip = yield userm.check_phone_is_vip(phone, current_time)
            if is_vip == "1":
                # user_type = yield userm.check_phone_is_couch(phone)
                today_added = yield userm.check_today_added(phone)
                if today_added:
                    res = {"code": "1", "msg": u"今天已经获得积分，不可重复获得"}
                else:
                    # add_socre = settings.ADD_SCORE['student_share'] if user_type == '0' else settings.ADD_SCCORE['teacher_share']
                    add_socre = userm.get_share_score_random()
                    new_score = yield userm.update_score_2_mysql(phone, 'add', add_socre)
                    yield userm.save_score_log(phone, add_socre, '2', current_time, '')
                    res = {"code": "0", "score": add_socre}
            else:
                res = {"code": "2", "msg": u"不是vip"}
        else:
            res = {"code": "3", "msg": u"分享加积分未开启"}

        is_couch = yield couchm.get_couch_auth_status(phone)
        if is_couch:
            today_couch_added = yield couchm.check_couch_today_added(phone)
            if not today_couch_added:
                yield couchm.add_couch_score(
                    phone,
                    '',
                    'share',
                    5
                )
        utiltool.response_write(self, res)


class ScoreListHandler(APIRequestHandler):
    """积分明细"""
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        # 0: 减
        # 1：分享后新用户开通vip
        # 2：分享
        phone = self.get_argument('phone', '')
        pubtime = self.get_argument('pubtime', '')
        page_count = self.get_argument('page_count', '20')
        score = yield userm.get_user_scre(phone)
        score_list = yield userm.get_score_list(phone, pubtime, page_count)
        for item in score_list:
            if item['type'] == 5:
                item['type'] = 1
        res = {"code": "0", "score": score['score'], "info": score_list}
        utiltool.response_write(self, res)


class GetCashHandler(APIRequestHandler):
    """提现（生成兑换码）"""
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        GET_CASH_OPEN = 1
        if GET_CASH_OPEN:
            current_time = timetool.get_timestamp()
            phone = self.get_argument('phone', '')
            money = self.get_argument('money', '0')
            is_vip1 = yield userm.check_phone_is_vip1(phone, current_time)
            is_vip4 = yield userm.check_phone_is_vip4(phone, current_time)
            is_couch = yield couchm.get_couch_auth_status(phone)
            if is_vip1 == "1" or is_vip4 == "1" or is_couch:
                MIN_MONEY = 20 if is_couch else 5
                if float(money) >= MIN_MONEY:
                    score_enough = yield userm.check_scre_enough(phone, float(money))
                    if score_enough:
                        res = yield wechatm.send_red_to_phone(phone, money)
                        if res == 1:
                            new_score = yield userm.update_score_2_mysql(phone, 'min', float(money))
                            yield userm.save_score_log(phone, money, 0, current_time)
                            res = {"code": "0", "score": new_score}
                        elif res == 2:
                            res = {"code": "1", "msg": u"请关注公众号启程一点通并绑定手机号"}
                        else:
                            res = {"code": "1", "msg": u"发送失败"}
                    else:
                        res = {"code": "1", "msg": u"额度不足"}

                else:
                    res = {"code": "1", "msg": u"提现金额不能小于{}元".format(MIN_MONEY)}
            else:
                res = {"code": "1", "msg": u"您不是VIP或教练"}
        else:
            res = {"code": "1", "msg": u"提现功能将于2018年1月份开通"}
        utiltool.response_write(self, res)


class GetVersionHandler(APIRequestHandler):
    """判断版本更新"""
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        version = self.get_argument('version', '1.0')
        device_type = self.get_argument('device_type', '0')
        last_version = yield userm.get_last_version(device_type)
        if device_type == '0':
            del last_version['check_version']
        else:
            last_version['check_version'] = 0 if version >= last_version['check_version'] else 1
        if last_version['version'] > version:
            res = {"code": "0", "info": last_version}
        else:
            res = {"code": "1", "msg": u"您已经是最新版本"}
        if device_type == '1':
            res['info'] = last_version
        utiltool.response_write(self, res)


class GetVipCntHandler(APIRequestHandler):
    """VIP用户总数"""
    @checktool.check_sign
    @gen.coroutine
    def get(self):
        cnt = yield userm.get_vip_cnt()
        base_cnt = yield userm.get_base_cnt()
        res = {"code": "0", "cnt": cnt + base_cnt['vip_base_cnt']}
        utiltool.response_write(self, res)


class CheckwxbindHandler(APIRequestHandler):
    """微信号中判断有没有绑定手机号"""
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        code = self.get_argument('code', '')
        open_id = yield paym.get_openid_with_code(code)
        print open_id
        phone = ""
        if open_id:
            phone = yield userm.check_wx_bind(open_id)
        is_bind = 1 if phone else 0
        info = dict(
            is_bind=is_bind,
            phone=phone,
            open_id=open_id
        )
        res = {"code": "0", "info": info}
        utiltool.response_write(self, res)


class WbindHandler(APIRequestHandler):
    """微信号中绑定手机号"""
    @checktool.check_sign
    @payt.check_id_code
    @gen.coroutine
    def post(self):
        open_id = self.get_argument('open_id', '')
        phone = self.get_argument('phone', '')
        current_time = timetool.get_timestamp()
        yield userm.bind_wx_phone(phone, open_id)
        user_info = yield userm.get_userinfo_with_phone(phone)
        if user_info:
            pass
        else:
            sj_name = yield userm.get_sj_nick_name()
            yield userm.add_user_info(0, phone, '', sj_name, settings.DEFAULT_AVATAR, 2, current_time, '3', '')
        res = {"code": "0", "msg": u"绑定成功"}
        utiltool.response_write(self, res)


class CheckMsgHandler(APIRequestHandler):
    """检查我的消息红点"""
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        phone = self.get_argument('phone', '')
        last_notice = yield userm.get_last_notice_time()
        if phone:
            last_reply = yield userm.get_last_reply_time(phone, 0)
            last_zan = yield userm.get_last_zan_time(phone, 0)
            last_couch_reply = yield userm.get_last_reply_time(phone, 1)
            last_couch_zan = yield userm.get_last_zan_time(phone, 1)
            last_consult = yield userm.get_last_consult_time(phone)
        else:
            last_reply = 0
            last_zan = 0
            last_couch_reply = 0
            last_couch_zan = 0
            last_consult = 0

        info = dict(
            last_notice=last_notice,
            last_reply=last_reply,
            last_zan=last_zan,
            last_couch_reply=last_couch_reply,
            last_consult=last_consult,
            last_couch_zan=last_couch_zan
        )
        res = {"code": "0", "info": info}
        utiltool.response_write(self, res)
